import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:kudos/config/widget_config.dart';
import 'package:kudos/core/utils/kudo_colors.dart';
import 'package:kudos/core/utils/kudo_login.dart';
import 'package:kudos/core/utils/kudo_url.dart';
import 'package:kudos/core/widget/loading_widget.dart';
import 'package:loading_animation_widget/loading_animation_widget.dart';
import '../../state/person/persona_session_controller.dart';
import '../../utils/kudo_helper.dart';
import '../../router/app_navigation_manager.dart';

class CredentialEntryScreen extends StatefulWidget {
  const CredentialEntryScreen({super.key});

  @override
  State<CredentialEntryScreen> createState() => _CredentialEntryScreenState();
}

class _CredentialEntryScreenState extends State<CredentialEntryScreen> {
  final TextEditingController _accountInputController = TextEditingController();
  final TextEditingController _passwordInputController =
      TextEditingController();
  final GlobalKey<FormState> _formValidationKey = GlobalKey<FormState>();

  bool _isProcessingAuthentication = false;
  bool _isPasswordVisible = false;
  String? _accountValidationError;
  String? _passwordValidationError;

  @override
  void dispose() {
    _accountInputController.dispose();
    _passwordInputController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/background.png'),
            fit: BoxFit.fill,
          ),
        ),
        child: [
          _buildNavigationHeaderSection(),

          _buildBrandingSection().paddingTop(10.h),

          SizedBox(height: 55.h),

          Expanded(child: _buildAuthenticationFormSection()),
        ].toColumn().safeArea(bottom: false),
      ),
    );
  }

  Widget _buildNavigationHeaderSection() {
    return [
          Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black,
            size: 20.w,
          ).inkWell(onTap: () => Navigator.of(context).pop()),
        ]
        .toRow(mainAxisAlignment: MainAxisAlignment.start)
        .paddingHorizontal(16.w)
        .paddingTop(20.h);
  }

  Widget _buildBrandingSection() {
    return [
      Container(
        width: 90.w,
        height: 90.w,
        decoration: BoxDecoration(
          image: DecorationImage(image: AssetImage('assets/images/logo.png')),
        ),
      ),

      Text('Kudos')
          .fontSize(28.sp)
          .fontWeight(FontWeight.w900)
          .fontFamily(GoogleFonts.montserrat().fontFamily)
          .textColor(KudoColors.black)
          .textShadow(
            color: KudoColors.yellow,
            blurRadius: 0,
            offset: const Offset(0, 4),
          )
          .paddingTop(10.h),
    ].toColumn();
  }

  Widget _buildAuthenticationFormSection() {
    return Container(
      width: double.infinity,
      height: double.infinity,
      decoration: BoxDecoration(
        color: const Color(0xFFFFF9C8),
        borderRadius: BorderRadius.only(
          topLeft: Radius.circular(30.r),
          topRight: Radius.circular(30.r),
        ),
      ),
      child: SingleChildScrollView(
        child: Form(
          key: _formValidationKey,
          child: [
            _buildAccountInputSection(),

            _buildPasswordInputSection(),
            SizedBox(height: 56.h),

            _buildLoginButtonSection(),

            _buildAppleSignInSection(),

            _buildRegistrationLinkSection(),

            SizedBox(height: 10.h),

            _buildTermsOfServiceSection(),
          ].toColumn().paddingHorizontal(20.w).paddingVertical(24.h),
        ),
      ),
    );
  }

  Widget _buildAccountInputSection() {
    return [
      Text(
        'Account',
      ).fontSize(16.sp).fontWeight(FontWeight.w600).textColor(Colors.black87),

      SizedBox(height: 8.h),

      Container(
        height: 51.h,
        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                _accountValidationError != null
                    ? Colors.red
                    : Colors.transparent,
            width: 2,
          ),
        ),
        child: TextField(
          controller: _accountInputController,
          decoration: InputDecoration(
            hintText: 'Nome Completo',
            hintStyle: TextStyle(color: Colors.black54, fontSize: 16.sp),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
          ),
          style: TextStyle(
            color: Colors.black87,
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ).configWidget(borderRadius: 12.r),

      if (_accountValidationError != null)
        Text(
          _accountValidationError!,
        ).fontSize(12.sp).textColor(Colors.red).paddingTop(4.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start);
  }

  /// 构建密码输入区域
  Widget _buildPasswordInputSection() {
    return [
      Text(
        'Password',
      ).fontSize(16.sp).fontWeight(FontWeight.w600).textColor(Colors.black87),

      SizedBox(height: 8.h),

      Container(
        height: 51.h,

        decoration: BoxDecoration(
          color: KudoColors.green,
          borderRadius: BorderRadius.circular(12.r),
          border: Border.all(
            color:
                _passwordValidationError != null
                    ? Colors.red
                    : Colors.transparent,
            width: 2,
          ),
        ),
        child: TextField(
          controller: _passwordInputController,
          obscureText: !_isPasswordVisible,
          decoration: InputDecoration(
            hintText: 'Password',
            hintStyle: TextStyle(color: Colors.black54, fontSize: 16.sp),
            suffixIcon: IconButton(
              icon: Icon(
                _isPasswordVisible ? Icons.visibility_off : Icons.visibility,
                color: Colors.black54,
                size: 20.w,
              ),
              onPressed: () {
                setState(() {
                  _isPasswordVisible = !_isPasswordVisible;
                });
              },
            ),
            border: InputBorder.none,
            contentPadding: EdgeInsets.symmetric(
              horizontal: 16.w,
              vertical: 16.h,
            ),
          ),
          style: TextStyle(
            color: Colors.black87,
            fontSize: 16.sp,
            fontWeight: FontWeight.w500,
          ),
        ),
      ).configWidget(borderRadius: 12.r),

      if (_passwordValidationError != null)
        Text(
          _passwordValidationError!,
        ).fontSize(12.sp).textColor(Colors.red).paddingTop(4.h),
    ].toColumn(crossAxisAlignment: CrossAxisAlignment.start).paddingTop(16.h);
  }

  Widget _buildLoginButtonSection() {
    return Container(
          width: double.infinity,
          height: 51.h,
          decoration: BoxDecoration(
            color: KudoColors.yellow,
            borderRadius: BorderRadius.circular(14.r),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withValues(alpha: 0.2),
                blurRadius: 8,
                offset: const Offset(0, 4),
              ),
            ],
          ),
          child:
              _isProcessingAuthentication
                  ? LoadingAnimationWidget.threeRotatingDots(
                    color: KudoColors.black,
                    size: 24.w,
                  ).center()
                  : Text('LOGIN')
                      .fontSize(18.sp)
                      .fontFamily(GoogleFonts.lato().fontFamily)
                      .fontWeight(FontWeight.bold)
                      .textColor(KudoColors.black)
                      .center(),
        )
        .configWidget(borderRadius: 14.r)
        .inkWell(
          onTap: _isProcessingAuthentication ? null : _executeLoginProcess,
        );
  }

  Widget _buildAppleSignInSection() {
    return Container(
      width: double.infinity,
      height: 51.h,
      margin: EdgeInsets.only(top: 12.h),
      decoration: BoxDecoration(
        color: Colors.black,
        borderRadius: BorderRadius.circular(12.r),
      ),
      child: [
        Icon(Icons.apple, color: Colors.white, size: 24.w),
        Text('Sign in with Apple')
            .fontSize(16.sp)
            .fontWeight(FontWeight.w600)
            .textColor(Colors.white)
            .paddingLeft(8.w),
      ].toRow(mainAxisAlignment: MainAxisAlignment.center),
    ).inkWell(onTap: _handleAppleSignIn);
  }

  Widget _buildRegistrationLinkSection() {
    return [
      Text('New User? ').fontSize(12.sp).textColor(Colors.black54),
      Text('Sign Up')
          .fontSize(12.sp)
          .fontWeight(FontWeight.w600)
          .fontFamily(GoogleFonts.lato().fontFamily)
          .textColor(const Color(0xFF39C888))
          .inkWell(onTap: _navigateToRegistration),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center).paddingTop(16.h);
  }

  Widget _buildTermsOfServiceSection() {
    return [
      Text(
        'By continuing, you agree to our ',
      ).fontSize(10.sp).textColor(Colors.black54),
      Text(
        'Terms of Service',
        style: TextStyle(
          fontSize: 10.sp,
          fontWeight: FontWeight.w600,
          color: Colors.black,
          decoration: TextDecoration.underline,
        ),
      ).inkWell(onTap: _showTermsOfService),
      Text(' and ').fontSize(10.sp).textColor(Colors.black54),
      Text(
        'EULA',
        style: TextStyle(
          fontSize: 10.sp,
          fontWeight: FontWeight.w600,
          color: Colors.black,
          decoration: TextDecoration.underline,
        ),
      ).inkWell(onTap: _showEULA),
    ].toRow(mainAxisAlignment: MainAxisAlignment.center).paddingTop(20.h);
  }

  void _executeLoginProcess() async {
    if (_accountValidationError != null || _passwordValidationError != null) {
      KudoToast.showWarningToast(context, 'Please fix the errors above');
      return;
    }

    final account = _accountInputController.text.trim();
    final password = _passwordInputController.text.trim();

    if (account.isEmpty || password.isEmpty) {
      KudoToast.showWarningToast(context, 'Please fill in all fields');
      return;
    }

    setState(() {
      _isProcessingAuthentication = true;
    });

    try {
      final success = PersonaSessionController.quickLogin(account, password);

      LoadingWidget.showLoadingDialog(
        context,
        message: 'Logging in...',
        color: KudoColors.green,
        animationType: LoadingAnimationType.threeRotatingDots,
      );

      await Future.delayed(const Duration(milliseconds: 2000));

      if (mounted) {
        // 先关闭loading对话框
        Navigator.of(context).pop();

        setState(() {
          _isProcessingAuthentication = false;
        });

        if (success) {
          KudoToast.showSuccessToast(context, 'Login successful');
          // 登录成功后返回上一个页面
          // 使用延迟确保Toast显示完成后再返回
          Future.delayed(const Duration(milliseconds: 500), () {
            if (mounted) {
              GoRouter.of(context).pop();
            }
          });
        } else {
          KudoToast.showErrorToast(context, 'Invalid account or password');
        }
      }
    } catch (e) {
      if (mounted) {
        // 先关闭loading对话框
        Navigator.of(context).pop();

        setState(() {
          _isProcessingAuthentication = false;
        });
        KudoToast.showErrorToast(context, 'Login failed: ${e.toString()}');
      }
    }
  }

  void _handleAppleSignIn() async {
    LoadingWidget.showLoadingDialog(
      context,
      message: 'Logging in...',
      color: KudoColors.green,
      animationType: LoadingAnimationType.threeRotatingDots,
    );

    await Future.delayed(const Duration(milliseconds: 2000));

    final result = await ApplePlugin.appleLogin();
    if (result) {
      final success = PersonaSessionController.quickLogin('admin', '123456');

      LoadingWidget.hideLoadingDialog(context);
      KudoToast.showSuccessToast(context, 'Login Successful.');
      GoRouter.of(context).pop();
    } else {
      LoadingWidget.hideLoadingDialog(context);
      KudoToast.showErrorToast(context, 'Login failed');
    }
  }

  /// 导航到注册页面
  void _navigateToRegistration() {
    AppNavigationManager.navigateToAccountCreation(context);
  }

  void _showTermsOfService() {
    KudoOpen.openTerms();
  }

  void _showEULA() {
    KudoOpen.openEula();
  }
}
